<template>
	<div class="cloud-sync-page w-full h-full relative" ref="cloudSyncPage">
		<div class="w-full py-3 h-fit flex">
			<div
				@click="handleSyncLocalToCloud"
				class="w-fit text-sm text-white cursor-pointer flex py-1 px-3 bg-blue-500 rounded-md shadow-md">
				<i class="bi bi-cloud-arrow-up-fill mr-1"></i>
				<span>将本地笔记同步到云端</span>
			</div>
			<div class="ml-3">
				<span class="text-sm text-gray-500 dark:text-gray-300">
					云端共：{{ cloudNoteList.length }} 条笔记
				</span>
			</div>
		</div>
		<div class="list w-full flex flex-wrap">
			<div class="h-fit p-5" v-for="note in cloudNoteList" :class="noteItemWidth" :key="note.id">
				<ly-note-item :note="note">
					<template #tools>
						<div
							@click.stop="handleSaveToLocal(note)"
							class="rounded-full flex items-center justify-center ml-2">
							<i class="bi bi-plus-circle text-sm" title="添加到本地"></i>
						</div>
						<div
							@click.stop="handleViewNote(note)"
							class="item rounded-full flex items-center justify-center ml-2">
							<i class="bi bi-info-circle text-sm" title="笔记详情"></i>
						</div>
						<div
							@click.stop="handleDeleteNote(note.id)"
							class="rounded-full flex items-center justify-center ml-2">
							<i class="bi bi-trash3 text-sm" title="在云端删除"></i>
						</div>
					</template>
				</ly-note-item>
			</div>
		</div>
		<!-- 返回顶部 -->
		<div
			title="返回顶部"
			@click="handleBackTop"
			v-show="backTopVisible"
			class="back-top w-8 h-8 fixed right-10 bottom-10 rounded-full shadow-lg bg-blue-500 z-30 cursor-pointer overflow-hidden">
			<div class="w-full h-full flex items-center justify-center">
				<i class="bi bi-rocket-fill text-white text-sm"></i>
			</div>
		</div>
	</div>
	<ly-dialog v-model="viewDialogVisible" title="笔记信息">
		<div class="p-3 text-gray-800">
			<span>ID：{{ viewNote.id }}</span>
		</div>
		<div class="p-3 text-gray-800">
			<span>标题：{{ viewNote.title }}</span>
		</div>
		<div class="p-3 text-gray-800">
			<span>创建时间：{{ viewNote.createTime }}</span>
		</div>
		<div class="p-3 text-gray-800">
			<span>最后修改时间：{{ viewNote.updateTime }}</span>
		</div>
	</ly-dialog>
	<ly-dialog v-model="deleteDialogVisible" title="警告">
		<div class="text-center text-red-500">笔记删除后将无法恢复，是否确认删除？</div>
		<template #footer>
			<ly-button
				class="mr-2"
				@click.stop="deleteDialogVisible = false"
				text="取消"
				type="default" />
			<ly-button @click="handleConfirmDelete" text="确认删除" type="primary" />
		</template>
	</ly-dialog>
</template>

<script name="CloudSync" lang="ts" setup>
import utilTip from '@/utils/util.tip';
import type { Note, NoteList } from '@/types';
import { useNoteStore } from '@/stores/noteStore';
import { useScreenStore } from '@/stores/screenStore';
import LyDialog from '@/components/LyDialog/index.vue';
import { useSettingStore } from '@/stores/settingStore';
import LyNoteItem from '@/components/LyNoteItem/index.vue';
import { deleteNoteFromCloudApi, getNoteListApi, syncLocalNoteToCloudApi } from '@/api';

const noteStore = useNoteStore();
const screenStore = useScreenStore();
const settingStore = useSettingStore();

// 云端笔记列表
const cloudNoteList = ref<NoteList>([]);

// 笔记项动态宽度
const noteItemWidth = computed<string>(() => {
	if (screenStore.screenSize === 'sm' || screenStore.screenSize === 'md') return 'w-1/2';

	if (screenStore.screenSize === 'xs') return 'w-full';

	return 'w-1/3';
});

// 返回顶部
const backTopVisible = ref<boolean>(false);
const cloudSyncPage = useTemplateRef<HTMLDivElement>('cloudSyncPage');
const handleBackTop = (): void => {
	cloudSyncPage.value?.scrollTo({ top: 0, behavior: 'smooth' });
};

// 保存到本地
const handleSaveToLocal = (note: Note): void => {
	const index = noteStore.noteList.findIndex((item) => item.id === note.id);
	if (index === -1) {
		noteStore.noteList.push(note);
		utilTip.success('笔记保存成功');
	} else {
		noteStore.noteList[index] = { ...note };
	}
};

// 将本地笔记同步到云端
const handleSyncLocalToCloud = async (): Promise<void> => {
	try {
		const notes = noteStore.noteList;
		const url = settingStore.cloudSyncUrl;
		const { safePassword } = settingStore.settingConfig;
		const res: any = await syncLocalNoteToCloudApi(url, safePassword, notes);
		if (res.code === 200) {
			await handleGetNoteListFromCloud();
			utilTip.success('同步成功');
		}
	} catch (error: any) {
		utilTip.error(`同步失败：${error.message}`);
	}
};

// 查看笔记详情
const viewNote = ref<Note>({
	id: '',
	title: '',
	content: '',
	createTime: '',
	updateTime: '',
});
const viewDialogVisible = ref<boolean>(false);
const handleViewNote = (note: Note): void => {
	viewNote.value = note;
	viewDialogVisible.value = true;
};

// 删除笔记
const deleteNoteId = ref<string>('');
const deleteDialogVisible = ref<boolean>(false);
const handleDeleteNote = (id: string): void => {
	deleteDialogVisible.value = true;
	deleteNoteId.value = id;
};
const handleConfirmDelete = async (): Promise<void> => {
	try {
		const url = settingStore.cloudSyncUrl;
		const { safePassword } = settingStore.settingConfig;
		const res: any = await deleteNoteFromCloudApi(url, safePassword, deleteNoteId.value);
		if (res.code === 200) {
			await handleGetNoteListFromCloud();
			utilTip.success('笔记删除成功');
		}
	} catch (error: any) {
		utilTip.error(`删除失败：${error.message}`);
	}
};

// 获取云端笔记列表
const handleGetNoteListFromCloud = async (): Promise<void> => {
	const url = settingStore.cloudSyncUrl;
	const { safePassword } = settingStore.settingConfig;
	if (url.trim().length < 1 || safePassword.trim().length < 1) {
		utilTip.error('请先配置云端同步信息');
		return;
	}
	try {
		// 获取云端笔记列表
		const res: any = await getNoteListApi(url, safePassword);
		if (res.code === 200) {
			cloudNoteList.value = res.list;
		}
	} catch (error: any) {
		utilTip.error(`获取失败：${error.message}`);
	}
	deleteDialogVisible.value = false;
};

onBeforeMount(async () => {
	await handleGetNoteListFromCloud();
});

onMounted(() => {
	cloudSyncPage.value?.addEventListener('scroll', () => {
		if (cloudSyncPage.value?.scrollTop && cloudSyncPage.value?.scrollTop > 200) {
			backTopVisible.value = true;
		} else {
			backTopVisible.value = false;
		}
	});
});

onBeforeUnmount(() => {
	cloudSyncPage.value?.removeEventListener('scroll', () => {});
});
</script>

<style lang="scss" scoped>
.cloud-sync-page {
	overflow-y: scroll;

	&::-webkit-scrollbar {
		width: 5px;
	}

	&::-webkit-scrollbar-thumb {
		cursor: pointer;
		border-radius: 5px;
		background-color: #ccc;
	}
}

html.dark {
	.cloud-sync-page {
		&::-webkit-scrollbar-thumb {
			background-color: #666;
		}
	}
}
</style>
